package com.maltys.backtracking;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author maltys
 * @link <a href="https://leetcode.cn/problems/non-decreasing-subsequences/">递增子序列</a>
 */
public class NonDecreasingSubsequences {
    public List<List<Integer>> findSubsequences(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        backTracing(nums, 0, new ArrayList<>(), res);
        return res;
    }

    private void backTracing(int[] nums, int idx, List<Integer> list, List<List<Integer>> res) {
        if (idx > nums.length) {
            return;
        }

        if (list.size() > 1) {
            res.add(new ArrayList<>(list));
        }

        Set<Integer> used = new HashSet<>();
        for (int i = idx; i < nums.length; i++) {
            if (!list.isEmpty() && nums[i] < list.get(list.size() - 1)) {
                continue;
            }
            if (used.contains(nums[i])) {
                continue;
            }
            list.add(nums[i]);
            used.add(nums[i]);
            backTracing(nums, i + 1, list, res);
            list.remove(list.size() - 1);
        }
    }

    public static void main(String[] args) {
        NonDecreasingSubsequences subsequences = new NonDecreasingSubsequences();
        List<List<Integer>> lists = subsequences.findSubsequences(new int[]{4, 6, 7, 7});
        lists.forEach(System.out::println);
    }
}
